package com.ctgu.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.project.entity.BlogsEntity;
import com.ctgu.project.entity.UsersEntity;
import com.ctgu.project.mapper.BlogsMapper;
import com.ctgu.project.response.GetUserDTO;
import com.ctgu.project.service.BlogsService;
import com.ctgu.project.service.UsersService;
import com.ctgu.project.utils.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author Alex2
* @description 针对表【t_blogs】的数据库操作Service实现
* @createDate 2025-02-27 17:28:26
*/
@Service
public class BlogsServiceImpl extends ServiceImpl<BlogsMapper, BlogsEntity>
    implements BlogsService {

    private static final String REDIS_KEY_BLOG_LIKES = "blog:likes:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UsersService usersService;

    /**
     * @Author: Alex
     * @Description: 点赞
     */
    @Override
    public ApiResult likeById(Integer userId, Integer id) {
        Double score = redisTemplate.opsForZSet().score(REDIS_KEY_BLOG_LIKES + id, userId.toString());
        //未点赞则点赞
        if (score == null) {
            update().setSql("likes = likes + 1").eq("id", id).update();
            redisTemplate.opsForZSet().add(REDIS_KEY_BLOG_LIKES + id, userId.toString(), System.currentTimeMillis());
            return ApiResult.success("点赞成功");
            //点赞则取消
        } else {
            update().setSql("likes = likes - 1").eq("id", id).update();
            redisTemplate.opsForZSet().remove(REDIS_KEY_BLOG_LIKES + id, userId.toString());
            return ApiResult.success("取消点赞成功");
        }
    }

    /**
     * @Author: Alex
     * @Description: 获取头5个点赞者
     */
    @Override
    public ApiResult getLikesLeaderBoardsById(Integer id) {
        // 查询top5的点赞用户 zrange key 0 4
        Set<String> top5 = redisTemplate.opsForZSet().range(REDIS_KEY_BLOG_LIKES + id, 0, 5);
        if (top5 == null || top5.isEmpty()) {
            return ApiResult.success("点赞列表为空", Collections.emptyList());
        }
        // 解析出其中的用户id
        List<Integer> ids = top5.stream().map(Integer::valueOf).collect(Collectors.toList());
        List<Object> userDTOs = new ArrayList<>();
        for (Integer userId : ids) {
            UsersEntity user = usersService.lambdaQuery().eq(UsersEntity::getId, userId).one();
            if (user != null) {
                userDTOs.add(BeanUtil.copyProperties(user, GetUserDTO.class));
            }
        }
        return ApiResult.success("获取点赞列表成功", userDTOs);
    }
}